package com.fox.hiring.talent.dao;

import java.io.IOException;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;

import com.fox.hiring.common.DBObject;
import com.fox.hiring.common.util.DBUtil;
import com.fox.hiring.talent.entity.TalentEntity;

/**
 * Talent Dao
 * 
 * @author fox.
 * @since 2016年2月26日
 */
public class TalentDao {

	/**
	 * 登录
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public TalentEntity login(String code, String password) {
		TalentEntity talent = null;
		String sql = "SELECT * FROM talent WHERE code=? AND password=?";
		DBObject dbObject = null;
		try {
			dbObject = DBUtil.executeQuery(sql, code, password);
			ResultSet resultSet = dbObject.getResultSet();
			while (resultSet.next()) {
				talent = new TalentEntity();
				talent.setId(resultSet.getInt("id"));
				talent.setCode(resultSet.getString("code"));
				talent.setName(resultSet.getString("name"));
				talent.setPhone(resultSet.getString("phone"));
				talent.setEmail(resultSet.getString("email"));
				talent.setAge(resultSet.getInt("age"));
				talent.setGender(resultSet.getInt("gender"));
				talent.setHobby(resultSet.getString("hobby"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(dbObject);
		}
		return talent;
	}

	/**
	 * 注册
	 * 
	 * @param talent
	 * @return
	 */
	public int register(TalentEntity talent) {
		int row = 0;
		String sql = "INSERT INTO talent VALUES(NULL, ?, ?, ?, ?, ?, ?, ?, ?)";
		try {
			List<Object> paramList = new ArrayList<>();
			paramList.add(talent.getCode());
			paramList.add(talent.getPassword());
			paramList.add(talent.getName());
			paramList.add(talent.getPhone());
			paramList.add(talent.getEmail());
			paramList.add(talent.getAge());
			paramList.add(talent.getGender());
			paramList.add(talent.getHobby());
			row = DBUtil.executeUpdate(sql, paramList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return row;
	}

	/**
	 * 修改个人资料
	 * 
	 * @param talent
	 * @return
	 */
	public int update(TalentEntity talent) {
		int row = 0;
		String sql = "UPDATE talent SET name=?, phone=?, email=?, age=?, gender=?, hobby=? WHERE id=?";
		try {
			List<Object> paramList = new ArrayList<>();
			paramList.add(talent.getName());
			paramList.add(talent.getPhone());
			paramList.add(talent.getEmail());
			paramList.add(talent.getAge());
			paramList.add(talent.getGender());
			paramList.add(talent.getHobby());
			paramList.add(talent.getId());
			row = DBUtil.executeUpdate(sql, paramList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return row;
	}
}
